from flask   import Flask, request, jsonify
from limiter import acquire_user_slot, release_user_slot
from signals import request_finished
import time

app = Flask(__name__)

@app.route("/api/t1", methods=["GET", ])
def process_task():
    user_id = request.headers.get("X-USER-ID") or "anonymous"

    if not acquire_user_slot(user_id):
        return jsonify({"error": "Too many concurrent requests"}), 429

    try:
        # 模拟耗时任务
        time.sleep(5)
        result = {"message": f"Task complete for {user_id}"}
    finally:
        # 释放并发槽
        release_user_slot(user_id)
        # 发出任务完成信号
        request_finished.send("api/t1", user_id=user_id)
    return jsonify(result)

@app.route("/api/t2")
def process_task2():
    user_id = request.headers.get("X-USER-ID") or "anonymous"

    if not acquire_user_slot(user_id):
        return jsonify({"error": "Too many concurrent requests"}), 429

    try:
        # 模拟耗时任务
        time.sleep(10)
        result = {"message": f"Task complete for {user_id}"}
    finally:
        # 释放并发槽
        release_user_slot(user_id)
        # 发出任务完成信号
        request_finished.send("api/t2", user_id=user_id)

    return jsonify(result)

if __name__ == "__main__":
    app.run(host="0.0.0.0",port=5000, debug=True)
